'use client'
import { useEffect } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import Loading from '@/app/components/base/loading'
import Toast from '@/app/components/base/toast'

type LoginResponse = {
  code: number
  msg?: string
  data?: {
    access_token: string
    refresh_token: string
    user?: any
  }
}

const handleOAuthLogin = async (code: string) => {
  const ADMIN_API_PREFIX = process.env.NEXT_PUBLIC_ADMIN_API_PREFIX
  if (!ADMIN_API_PREFIX)
    throw new Error('认证服务器地址未配置')

  try {
    const res = await fetch(`${ADMIN_API_PREFIX}/base/oaLoginByIlink`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ code }),
    })
    return res.json()
  }
  catch (error) {
    console.error('OAuth login error:', error)
    throw error
  }
}

const OAuthPage = () => {
  const router = useRouter()
  const searchParams = useSearchParams()
  const code = searchParams.get('code')

  // 借助ilink完成统一身份登录，保证两个平台的用户userId部分一致

  useEffect(() => {
    // 如果没有code参数，说明是首次进入页面，需要重定向到ilink登录页
    if (!code) {
      const currentUrl = window.location.href
      console.log(currentUrl)
      const ilinkUrl = `${process.env.NEXT_PUBLIC_ILINK_URL}/oauth3?redirect=${encodeURIComponent(currentUrl)}`
      window.location.href = ilinkUrl
      return
    }
    // 如果有code，说明是从ilink重定向回来的，需要调用go后端接口
    handleOAuthLogin(code).then((res) => {
      if (res.code === 0) {
        // 存储token
        localStorage.setItem('console_token', res.data?.access_token || '')
        localStorage.setItem('refresh_token', res.data?.refresh_token || '')
        // 跳转到应用列表
        router.push('/apps')
      }
      else {
        Toast.notify({
          type: 'error',
          message: res.msg || '登录失败',
        })
        router.push('/signin')
      }
    }).catch((error) => {
      console.error('OAuth login error:', error)
      Toast.notify({
        type: 'error',
        message: error.message || '登录失败',
      })
      router.push('/signin')
    })
  }, [code, router])

  return (
    <div className="flex h-screen w-full items-center justify-center">
      <Loading type='area' />
    </div>
  )
}

export default OAuthPage
